/**
 * @ author: 汪孟苹
 */
define(["jquery","bbcare","fu/app/comm/comm","fu/app/comm/validate","fu/app/comm/attention",
	"scprit/followup/app/question/question.ui.js",
	"scprit/followup/app/question/question.event.js",
	"scprit/followup/app/datatable/datatable.ui.js",
	"scprit/followup/app/specialNurse/specialNurse.servers.js",
    "scprit/followup/app/specialNurse/specialNurse.ui.js"],
    function ($,$bb,$comm,$validate,$attention,$questionUi,$questionEvent,$datatableUi,$specialNurseServers,$specialNurseUi) {
    var event = {};

    /**
     * 新建档 （添加患者）
     */
    var onSaveArchive = function(){
    	var preTime = $(this).attr("preTime");
    	var time = new Date().getTime();
		$(this).attr("preTime",time);
		if( (!preTime) || (preTime && time - preTime > 1000) ){
			if( $validate.init() ){
				var params = $(this).data("params");
				$specialNurseServers.ajaxPatientAddNew(params,init);
			}
		}
    }

    /**
	 * 修改建档信息
	 */
	var onModifyArchive = function(){
		var preTime = $(this).attr("preTime");
		var time = new Date().getTime();
		$(this).attr("preTime",time);
		if( (!preTime) || (preTime && time - preTime > 1000) ){
			if( $validate.init() ){
				var params = $(this).data("params");
				$specialNurseServers.ajaxModifyArchives(params,init);
			}
		}
	}

    /**
	 * 请求建档问卷成功后的回调函数
	 */
	var ajaxQueueArchiveContentCallBack = function(data,params,req){
		$specialNurseUi.archiveInit({
			"id":"specialNurseContentWrap",
		});
		var questValues,schemeListValues;
		if(data.archivesInfo){
			questValues = data.archivesInfo.values;
			schemeListValues = data.archivesInfo.schemeList;
		}
		$questionUi.init({
        	id: "specialNurseArchive",
        	status: "default",
            list: data.questiones,	  // 问卷
            values: $comm.handleValue(data.patientInfo,questValues),
            initParams:{
            	queueId:params.followQueueId
            }
        });
        params = $.extend(params,{"schemeBusiType":1});
        $questionEvent.init({
        	"getPatientsByPhone":{
	        	"params":params,
	        	"callback":init
	        },
	        "getGeneFusion":{
				"followQueueId":params.followQueueId,
				"values":questValues
			}
        });
        $attention.init();
        $('.validatebox').data("attentionFun",$attention.blurInit);	// 校验之前提醒
        $validate.blurInit();
        $specialNurseUi.schemeInit({
			"id":"specialNurseScheme",
			"status": "default",
			"list":req.schemeList,
			"queueName":req.queueName,
			"values":schemeListValues
		});
        // 保存
        var topbars;
        if(params.ptSchemeId){
        	topbars = [
				{
					"icon":"fa fa-floppy-o",
					"name":"保存",
					"callback":onModifyArchive,
					"params":params
				}
			];
        }else{
        	topbars = [
				{
					"icon":"fa fa-floppy-o",
					"name":"保存",
					"callback":onSaveArchive,
					"params":params
				}
			];
		}
		$bb.toolbar(topbars);
	}

    /**
	 * 请求队列方案成功后的回调函数
	 */
	var ajaxQueueSchemeCallBack = function(data,params){
		$specialNurseServers.ajaxQueueArchiveContent(params,ajaxQueueArchiveContentCallBack,data);
	}

	/**
	 * 点击今日门诊里的列表
	 */
	var onListRedis = function(){
		var params = $(this).data("params");
		var ptSchemeId = $(this).attr("ptSchemeid");
		var patientId = $(this).attr("patientId");
		$.extend(params,{"ptSchemeId":ptSchemeId,"patientId":patientId});
		init(params);
	}

	/**
	 * 请求今日门诊列表成功后的回调函数
	 */
	var ajaxOperateListRedisCallBack = function(data,params){
		$specialNurseServers.ajaxQueueScheme(params,ajaxQueueSchemeCallBack);
		$specialNurseUi.rightOutpatientRecordsInit({
			"id":"specialNurseTabBar",
			"list":data.rows,
			"curPatient":params.ptSchemeId
		});
		$("#specialNurseTabBar li").unbind("click");
		$("#specialNurseTabBar li").data({"params":params});
		$("#specialNurseTabBar li").click(onListRedis);
	}

	/**
	 * 请求任务提交成功后的回调函数
	 */
	var ajaxSubmitTaskCallBack = function(data,params){
		$.extend(params,{"ptTaskId":data.ptTaskId});
		init(params);
	}

	/**
	 * 任务提交、任务修改
	 */
	var onSaveTask = function(){
		var preTime = $(this).attr("preTime");
		var time = new Date().getTime();
		$(this).attr("preTime",time);
		if( (!preTime) || (preTime && time - preTime > 1000) ){
			if( $validate.init() ){
				var params = $(this).data("params");
				$specialNurseServers.ajaxSubmitTask(params,ajaxSubmitTaskCallBack);
			}
		}
	}

	/**
	 * 请求任务模板、任务详情成功后的回调函数
	 */
	var ajaxOprationHisResourceCallBack = function(data,params){
		var defTaskRecordName = data.defTaskRecordName ? data.defTaskRecordName : params.taskRecordName;
		var values = {"Pub12x00010":defTaskRecordName};
		$.extend(values,data.values);
		$specialNurseUi.treatmentTask({
			"id":"specialNurseContentWrap",
			"defTaskRecordName":defTaskRecordName  // defTaskRecordName 、taskRecordName
		});
		$questionUi.init({
        	id: "specialNurseContent",
        	status: "default",
            list: data.questiones,	  // 问卷
            values: values,
            initParams:{
            	queueId:params.followQueueId
            }
        });
		$questionEvent.init({
			"getTextareaAssess":{
				"userId":params.patientId,
				"taskId":params.taskid
			},
			"getImageProcessing":{
				"userId":params.patientId,
				"patientName":data.values["Pub1100002"],
				"number": data.values["Pub12x00007"] ? data.values["Pub12x00007"] : "", //诊疗卡号
				"addmissionNumber": data.values["Pub12x00008"] ? data.values["Pub12x00008"] : "", //住院号
				"gender":data.values["Pub1100003"] == "女" ? "F" : data.values["Pub1100003"] == "男" ? "M":"",
				"birthday":data.values["Pub1100004"]
			},
			"getGeneFusion":{
				"followQueueId":params.followQueueId,
				"values":values
			}
		});
        $attention.init();
        $('.validatebox').data("attentionFun",$attention.blurInit);	// 校验之前提醒
        $validate.blurInit();
        // 任务修改
        $.extend(params,{"patientName":data.values.Pub1100002});
        var topbars = [
			{
				"icon":"fa fa-floppy-o",
				"name":"保存",
				"callback":onSaveTask,
				"params":params
			}
		];
		$bb.toolbar(topbars);
	}

	/**
	 * 点击任务历史记录
	 */
	var onHistoryListSelect = function(){
		$("#specialNurse-task button.active").removeClass("active");
		$(this).parents("ul").find("span.name").removeClass("active");
		$(this).addClass("active");
		var params = $(this).data("params");
		var taskId = $(this).attr("taskId");
		var ptTaskId = $(this).attr("ptTaskId");
		var seqNo = $(this).attr("seqNo");
		var taskRecordName = $(this).html();
		$.extend(params,{"taskid":taskId,"ptTaskId":ptTaskId,"taskRecordName":taskRecordName});
		$.extend(params.options,{"curIndex":seqNo});
		if(seqNo == 0){
			$specialNurseServers.ajaxQueueScheme(params,ajaxQueueSchemeCallBack);
		}else{
			$specialNurseServers.ajaxOprationHisResource(params,ajaxOprationHisResourceCallBack);
		}
	}

	/**
	 * 请求门诊任务历史记录列表成功后的回调函数
	 */
	var ajaxHistoryListCallBack = function(data,params){
		if(data.rows){
			if(!params.ptTaskId) params.ptTaskId = $specialNurseServers.getArchivePtTaskId(data.rows);
			$specialNurseUi.rightInit({
				"id":"specialNurseTabBar",
				"data":data,
				"ptTaskId":params.ptTaskId
			});
			// 时间轴折叠
			$(".name-box i.timeLine-fold").click(function(){
				if( $(this).hasClass("fa-plus-square-o") ){
					var len = $(this).prev("div").children("span").length;
					$(this).prev("div").css("height",20*len+"px");
					$(this).parents("li").css("height",40+20*(len-1)+"px");
					$(this).removeClass("fa-plus-square-o").addClass("fa-minus-square-o");
				}else if( $(this).hasClass("fa-minus-square-o") ){
					$(this).prev("div").css("height",20+"px");
					$(this).parents("li").css("height",40+"px");
					$(this).removeClass("fa-minus-square-o").addClass("fa-plus-square-o");
				}
			});
			$("#specialNurseTabBar .medical-record li span.name").unbind("click");
			$("#specialNurseTabBar .medical-record li span.name").data({"params":params});
			$("#specialNurseTabBar .medical-record li span.name").click(onHistoryListSelect);
			$("#specialNurseTabBar .medical-record li span.name[ptTaskId="+ params.ptTaskId +"]").click();
		}else{
			$bb.toastShow("该患者不在该队列中，请在该队列重新建档！");
		}
	}

	/********************  begin 南方医院添加 上传资料  ********************/
	/**
	 * 上传文件成功后的回调函数
	 */
	var uploadMultiFilesCallBack = function(data){
		$bb.toastShow("上传成功！");
		$datatableUi.table.api().ajax.reload();  // 出发dt的重新加载数据的方法
	}

	/**
	 *  input type=file发生变化时，触发的方法
	 *  南方医院添加 上传资料 wmp 2018-03-12 20:00 add
	 */
	var onUploadFiles = function(){
		var params = $(this).data("params");
    	var files = this.files;
    	var fd = new FormData();
		var fileInfo = [];
        for (var i = 0; i < files.length; i++){
        	fd.append("file["+i+"]",files[i]);
			fileInfo.push({
				"fileName": files[i].name,
                "fileCreateTime": $comm.getDateFormat(files[0].lastModifiedDate).locale,
                "fileModifyTime": $comm.getDateFormat(new Date(files[0].lastModified)).locale,
                "size": files[i].size,
                "type": files[i].type
			});
        }
        var params1 = {
        	"opCode":"2119",
	        "opNote":"南方医院文件上传",
	        "opType":"2",
        };
        $.extend(params1,params);
        var data = {
        	"data":params1
        }
        data.data.FileInfo = fileInfo;
		fd.append("data",JSON.stringify(data));
		$specialNurseServers.uploadMultiFiles(fd,uploadMultiFilesCallBack);
	}

	/********************  end 南方医院添加 上传资料  ********************/

	/**
	 * 点击任务card
	 */
	var onNavBarSelect = function(){
		$(this).addClass("active").siblings().removeClass("active");
		$("#specialNurseTabBar .medical-record li span.name.active").removeClass("active");
		var params = $(this).data("params");
		var curIndex = $(this).attr("seqNo");
		var picture = $(this).attr("picture");
		options = $.extend(params.options,{"curIndex":curIndex});
		if( curIndex ){
			if(curIndex == "0"){
				var params1 = {"followQueueId":params.followQueueId};
				if(params.ptSchemeId){
					$bb.toastConfirmShow(init,params1,"您确定要退出当前患者吗？");
				}else{
					init(params1);
				}
			}else{
				var taskId = $(this).attr("taskId");
				$.extend(params,{"taskid":taskId,"taskRecordName":"","ptTaskId":""});
				$specialNurseServers.ajaxTaskContent(params,ajaxOprationHisResourceCallBack);
			}
		}else if( picture ){//图片展示
			var params2;
			if(picture == "2"){
				params2 = {
				"schemeBusiType": "1",
		        "bindFlag": "bindFlag",
		        "userId": params.patientId,
		        "patientId": "patientId"
				};
	
			}else{
				params2 = {
					"schemeBusiType": "1",
		       		"userId": params.patientId,
		        	"ptSchemeId": params.ptSchemeId,
		       		"patientName":params.patientName,      	
				};
			}

			$specialNurseUi.picInfoInit({
				"id":"specialNurseContentWrap",
			});
		
			$datatableUi.init({
            "id": "pastFiles",
            "options": $specialNurseServers.getPicOptions(params2)
        	});
			

		}else{ // 南方医院添加 上传资料 wmp 2018-03-12 17:15 add
			var params2 = {
				"schemeBusiType": "1",
		        "userId": params.patientId,
		        "ptSchemeId": params.ptSchemeId,
		        "queueId": params.followQueueId,
			};
			$specialNurseUi.uploadInfoInit({
				"id":"specialNurseContentWrap",
			});
			$datatableUi.init({
	            "id": "pastFiles",
	            "options": $specialNurseServers.getOptions(params2)
	        });
			$("#uploadInfo input[type=file]").unbind("change");
			$("#uploadInfo input[type=file]").data({"params":params2});
			$("#uploadInfo input[type=file]").change(onUploadFiles);
		}
	}

	/**
	 * specialNurse-task 渲染
	 */
	var specialTaskInit = function(data,params){
		var options = {
			"id":"specialNurse-task",
			"curIndex":0,	// 默认进来是建档页
			"data":data.rows,
		};
		if(params.ptSchemeId) options = $.extend(options,{"patientName":params.patientName});
		$specialNurseUi.tabsInit(options);
		if(!params.ptSchemeId) $("#specialNurse-task button").eq(0).addClass("active");
		$("#specialNurse-task .pageTab .btn-toolbar button").unbind("click");
		$("#specialNurse-task .pageTab .btn-toolbar button").data({"params":params});
		$("#specialNurse-task .pageTab .btn-toolbar button.btn-click").click(onNavBarSelect);
		return options;
	}

    /**
	 * 请求诊疗任务成功后的回调函数
	 */
	var ajaxSpecialTaskCallBack = function(data,params){
		var options = specialTaskInit(data,params);
		if(!params.options) $.extend(params,{"options":options});
		if(params.ptSchemeId){
			$specialNurseServers.ajaxHistoryList(params,ajaxHistoryListCallBack);
		}else{
			$specialNurseServers.ajaxOperateListRedis(params,ajaxOperateListRedisCallBack);
		}
	}

	/**
	 * 请求患者基本信息成功后的回调函数
	 */
	var ajaxPatientInfoCallBack = function(data,params){
		if( data ) $.extend(params,{"patientName":data.PatientInfo.userName});
		$specialNurseServers.ajaxSpecialTask(params,ajaxSpecialTaskCallBack);
	}

	/**
	 * 初始化入口
	 */
	var init = function(params,result){
		if(result) { // 从根据手机号码搜索而来、新建档之后而来
			var patientId = result.id ? result.id : result.patientId; 
			$.extend(params,{"ptSchemeId":result.ptSchemeId,"patientId":patientId});
			delete params.ptTaskId;
		}
		if(params.ptSchemeId){
			$specialNurseServers.ajaxPatientInfo(params,ajaxPatientInfoCallBack);
		}else{
			ajaxPatientInfoCallBack(null,params);
		}
	}
	event.init = function(){
		var pageParams = $specialNurseServers.getPageParams();
		var params = {followQueueId:pageParams.followQueueId};
		if(pageParams.ptSchemeId) $.extend(params,{ptSchemeId:pageParams.ptSchemeId,patientId:pageParams.patientId});
		if(pageParams.ptTaskId) $.extend(params,{ptTaskId:pageParams.ptTaskId});
		init(params);
	}

    return event;
});